package com.abel.main.colony;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @author abel.he
 * @data 2018/8/9 23:10
 */
public class Consumer {

    public static void main(String[] args) {
        onMessage();
    }

    private static void onMessage() {
        ConnectionFactory factory = null;
        Connection connection = null;
        Session session = null;
        Destination destination = null;
        MessageConsumer consumer = null;

        try {
            factory = new ActiveMQConnectionFactory("admin", "admin",
                    "failover:(tcp://192.168.26.50:61616,tcp://192.168.26.50:61617,tcp://192.168.26.50:61618)?Randomize=false");
            connection = factory.createConnection();
            connection.start();

            session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
            destination = session.createQueue("colony");
            consumer = session.createConsumer(destination);
            consumer.setMessageListener(new MessageListener() {
                public void onMessage(Message message) {
                    try {
                        message.acknowledge();
                        TextMessage textMessage = (TextMessage) message;
                        System.out.println("收到的消息是： " + textMessage.getText());
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            });
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (consumer != null) {
                try {
                    consumer.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
